import axios from 'axios'
import * as Message from "@/utils/message"

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const setToken = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (localStorage.getItem("token") && !isToken) {
    config.headers['token'] = localStorage.getItem("token") // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  if(process.env.NODE_ENV === "development"){
    config.headers['token'] = "OWl4dWxld3hhbHNmbG5lYmNuc3drZXlkbHg2czYxODg1" // 让每个请求携带自定义token 请根据实际情况自行修改
  }
}

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: "",
  // 超时
  timeout: 1000 * 60 * 5
})
let loading = null;
// request拦截器
service.interceptors.request.use(config => {
  // 显示loading
  if (!config.hideLoading && !loading) loading = Message.loading();
  // 设置 token
  setToken(config);
  // get请求映射params参数
  if (config.method === 'get' && config.data) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.data)) {
      const value = config.data[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let data = propName + '[' + key + ']';
            var subPart = encodeURIComponent(data) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.data = {};
    config.url = url;
  }
  return config
}, error => {
  Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(res => {
    console.log('success', res)
    if (loading) {
      Message.clear();
      loading = null;
    }
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    const msg = res.data.msg;
    if (code === 401) {
      if (!res.config.hideMsg) Message.error("登录失效，请重新进入");
      return Promise.reject(new Error(msg))
    } else if (code === 500) {
      if (!res.config.hideMsg) Message.error(msg);
      return Promise.reject(new Error(msg))
    } else if (code === 505) {
      return Promise.reject(res.data)
    } else if (code !== 200) {
      if (!res.config.hideMsg) Message.error(msg);
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    if (loading) {
      loading.clear();
      loading = null;
    }
    console.log('err', error)
    let {
      message
    } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message.error(message);
    return Promise.reject(error)
  }
)

export default service